<?php
class Kal_Timetables_Block_Cat extends Mage_Core_Block_Template
{
    public function getPosts()
   	{	
		$cats = Mage::getSingleton('timetables/cat');
		if ($cats->getCatId() == NULL)
		{
			return false;
		}
		else
		{
			$page = (int)$this->getRequest()->getParam('page');
			$posts = Mage::getModel('timetables/timetables')->getCollection()
			->addStoreFilter(Mage::app()->getStore()->getId())
			->addCatFilter($cats->getCatId())
			->setOrder('created_time', 'desc');
			Mage::getSingleton('timetables/status')->addEnabledFilterToCollection($posts);
			//Mage::getSingleton('timetables/status')->addCatFilterToCollection($posts, $cats->getCatId());
			
			$posts->setPageSize((int)Mage::getStoreConfig('timetables/timetables/perpage'));
        	$posts->setCurPage($page);
			
			$route = Mage::getStoreConfig('timetables/timetables/route');
			if ($route == "")
			{
				$route = "timetables";
			}
			
			foreach ($posts as $item) 
			{
				$item->setAddress($this->getUrl($route) . 'cat/' . $cats->getIdentifier() . '/post/' . $item->getIdentifier());
				
				$item->setCreatedTime($this->formatDate($item->getCreatedTime(),Mage::getStoreConfig('timetables/timetables/dateformat')));
				$item->setUpdateTime($this->formatDate($item->getUpdateTime(),Mage::getStoreConfig('timetables/timetables/dateformat')));
				
				if ((int)Mage::getStoreConfig('timetables/timetables/readmore') != 0)
				{
					$content = $item->getPostContent();
					$content = strip_tags($content);
					if(strlen($content) >= (int)Mage::getStoreConfig('timetables/timetables/readmore'))
					{
						$content = substr($content, 0, (int)Mage::getStoreConfig('timetables/timetables/readmore'));
						$content = substr($content, 0, strrpos($content, ' '));
						$content = $this->closetags($content);
						$content .= ' ...&nbsp;&nbsp;<a href="' . $this->getUrl($route) . $item->getIdentifier() . '" >Read More</a>';
					}
					$item->setPostContent($content);
				}
				
				$comments = Mage::getModel('timetables/comment')->getCollection()
				->addPostFilter($item->getPostId())
				->addApproveFilter(2);
				$item->setCommentCount(count($comments));
				
				$inCats = Mage::getModel('timetables/cat')->getCollection()
				->addPostFilter($item->getPostId());
				$catUrls = array();
				foreach($inCats as $cat)
				{
					$catUrls[$cat->getTitle()] = Mage::getUrl($route . "/cat/") . $cat->getIdentifier();
				}
				$item->setCats($catUrls);
				}
				$this->setData('cat', $posts);
				return $this->getData('cat');
		}
        return false;
    }
	
	public function getBookmarkHtml($post)
	{
		if (Mage::getStoreConfig('timetables/timetables/bookmarkslist'))
		{
			$this->setTemplate('timetables/bookmark.phtml');
			$this->setPost($post);
			return $this->toHtml();
		}
		return;
	}
	
	public function getCommentsEnabled()
   	{
		return Mage::getStoreConfig('timetables/comments/enabled');
	}
	
	public function getCat()
   	{	
		$cats = Mage::getSingleton('timetables/cat');
		return $cats;
	}
	
	public function getPages()
	{
		if ((int)Mage::getStoreConfig('timetables/timetables/perpage') != 0)
		{
			$collection = Mage::getModel('timetables/timetables')->getCollection()
			->addStoreFilter(Mage::app()->getStore()->getId())
			->setOrder('created_time ', 'desc');
			
			$cats = Mage::getSingleton('timetables/cat');
			
			Mage::getSingleton('timetables/status')->addEnabledFilterToCollection($collection);
			Mage::getSingleton('timetables/status')->addCatFilterToCollection($collection, $cats->getCatId());
			
			$currentPage = (int)$this->getRequest()->getParam('page');
			$cat = $this->getRequest()->getParam('identifier');
	
			if(!$currentPage)
			{
				$currentPage = 1;
			}
			
			$route = Mage::getStoreConfig('timetables/timetables/route');
			if ($route == "")
			{
				$route = "timetables";
			}
			
			$pages = ceil(count($collection) / (int)Mage::getStoreConfig('timetables/timetables/perpage'));
			
			$links = "";
			
			$collectionfrom=($currentPage-1)*(int)Mage::getStoreConfig('timetables/timetables/perpage')+1;
			$collectionto=$collectionfrom+(int)Mage::getStoreConfig('timetables/timetables/perpage')-1;
			if($collectionto>count($collection)){
				$collectionto=count($collection);
			}
			//$links = $links . '<td align="left">Showing results ';
			//$links = $links . $collectionfrom.' to '.$collectionto.' of '.count($collection);
			//$links = $links . '</td>';
			//$links = $links . '<td align="right"> Page Number: ';
			if ($currentPage > 1)
			{
				$links = $links . ' <a href="' . $this->getUrl($route . '/cat') . $cat . '/page/' . (1) . '" class="timetables_page_nav">&lt; &lt; First</a> | ';
				$links = $links . ' <a href="' . $this->getUrl($route . '/cat') . $cat . '/page/' . ($currentPage - 1) . '" class="timetables_page_nav">&lt; Back</a> ';
			}
			//$links = $links . '<div class="right">';
			for($i=1;$i<=$pages;$i++){
				if($currentPage==$i){
					$links = $links . ' '.$i.' ';
				}else{
					$links = $links . ' <a href="' . $this->getUrl($route . '/cat') . $cat . '/page/' . ($i) . '" class="timetables_page_nav">'.$i.'</a> ';
				}
			}
			//$links = $links . '</div>';
			if ($currentPage < $pages)
			{
				$links = $links .  ' <a href="' . $this->getUrl($route . '/cat') . $cat . '/page/' . ($currentPage + 1) . '" class="timetables_page_nav">Next &gt;</a> ';
				$links = $links .  ' | <a href="' . $this->getUrl($route . '/cat') . $cat . '/page/' . ($pages) . '" class="timetables_page_nav">Last &gt; &gt;</a> ';
			}
			//$links = $links . '</tr></table>';
			//$links = $links . '</div>';
			echo $links;
		}
	}
	
	protected function _prepareLayout()
    {
        $post = $this->getCat();
		
		$route = Mage::getStoreConfig('timetables/timetables/route');
		if ($route == "")
		{
			$route = "timetables";
		}
		
		// show breadcrumbs
		if (Mage::getStoreConfig('timetables/timetables/timetablescrumbs') && ($breadcrumbs = $this->getLayout()->getBlock('breadcrumbs'))){
				$breadcrumbs->addCrumb('home', array('label'=>Mage::helper('timetables')->__('Home'), 'title'=>Mage::helper('timetables')->__('Go to Home Page'), 'link'=>Mage::getBaseUrl()));;
				$breadcrumbs->addCrumb('timetables', array('label'=>Mage::getStoreConfig('timetables/timetables/title'), 'title'=>Mage::helper('timetables')->__('Return to ' .Mage::getStoreConfig('timetables/timetables/title')), 'link'=>Mage::getUrl($route)));
				$breadcrumbs->addCrumb('timetables_page', array('label'=>$post->getTitle(), 'title'=>$post->getTitle()));
		}
		
		if ($head = $this->getLayout()->getBlock('head')) {
			$head->setTitle($post->getTitle());
			$head->setKeywords($post->getMetaKeywords());
			$head->setDescription($post->getMetaDescription());
		}
	}
	
	public function closetags($html)
	{
		#put all opened tags into an array
		preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
		$openedtags = $result[1];
	
		#put all closed tags into an array
		preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
		$closedtags = $result[1];
		$len_opened = count ( $openedtags );
		# all tags are closed
		if( count ( $closedtags ) == $len_opened )
		{
			return $html;
		}
		$openedtags = array_reverse ( $openedtags );
		# close tags
		for( $i = 0; $i < $len_opened; $i++ )
		{
			if ( !in_array ( $openedtags[$i], $closedtags ) )
			{
				$html .= "</" . $openedtags[$i] . ">";
			}
			else
			{
				unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
			}
		}
		return $html;
	}
}